import api from '@/network/api';
import { useRequest } from 'umi';
import React,{ useState } from 'react';
import { Table, Button,Popconfirm,message,Typography,Form,Input } from 'antd';
import { DeleteOutlined } from '@ant-design/icons';

const EditableCell = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  ...restProps
}) => {
  return (
    <td {...restProps}>
      {editable ? (
        <Form.Item
          name={dataIndex}
          style={{
            margin: 0,
          }}
          rules={[
            {
              required: true,
              message: `${title}不能为空`,
            },
          ]}
        >
          <Input />
        </Form.Item>
      ) : (
        children
      )}
    </td>
  )
}

const category: React.FC = () => {
  const [form] = Form.useForm();
  const [editingObjectId, seteditingObjectId] = useState('')
  const isEditing = (record) => record.objectId === editingObjectId;
  const { data, loading, error,refresh } = useRequest(() => {
    return api.getCateCake();
  });

  const edit = (record) => {
    form.setFieldsValue({
      ...record,
    });
    seteditingObjectId(record.objectId);
  }
  const cancel = () => {
    seteditingObjectId('');
  }
  const save = async (record) => {
    // 以下语句代表校验通过
    let res = await form.validateFields();
    if (res.errorFields) {
      message.error('校验失败');
    } else {
      let updateCateRes = await api.updateCateCake({
        objectId: record.objectId,
        ...res,
      });
      if (updateCateRes.code === 200) {
        refresh();
      }
    }
    // 校验通过后，进入下一步操作
    seteditingObjectId('');
  }

  const handleDelete = async (_,record,index) => {
    const res = await api.deleteCateCake({objectId: record.objectId});
    if (res.code === 200) {
      message.success('删除成功');
      // data.splice(index,1);
      // 触发刷新
      refresh();
      console.log('data',data,index)
    } else {
      message.error('删除失败');
    }
  }

  const columns = [
    {
      title: '分类名称',
      dataIndex: 'name',
      key: 'name',
      editable: true,
    },
    {
      width: '20%',
      title: '分类ID',
      dataIndex: 'objectId',
      key: 'objectId',
      editeable: false,
    },
    {
      title: '操作',
      width: '20%',
      align: 'center',
      render: (text,record,index) => {
        const editable = isEditing(record);
        return (
          <>
            <Popconfirm
              title="确定删除吗？"
              onConfirm={() => handleDelete(text,record,index)}
              okText="确定"
              cancelText="取消"
            >
              <Button 
                type="primary" 
                icon={<DeleteOutlined />} />
            </Popconfirm>
            {editable ? (
              <span className='editeable'>
                <Typography.Link
                  onClick={() => save(record)}
                  style={{
                    marginRight: 8,
                  }}
                >
                  Save
                </Typography.Link>
                <Popconfirm title="Sure to cancel?" onConfirm={cancel}>
                  <a>Cancel</a>
                </Popconfirm>
              </span>
            ) : (
          <Typography.Link 
          disabled={editingObjectId !== ''} 
          onClick={() => edit(record)}>
            Edit
          </Typography.Link>
            )}
          </>
        );
      },
    },
  ];
  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => {
        return {
          record,
          dataIndex: col.dataIndex,
          title: col.title,
          editable: isEditing(record),
        }
      },
    };
  });

  console.log('获取分类列表返回的数据', data);
  return (
    <Form form={form} component={false}>
      <Table
          components={{
            body: {
              cell: EditableCell,
            },
          }}
            columns={mergedColumns}
            dataSource={data}
            loading={loading}
            rowKey="objectId"
          />
    </Form>
  );
}

export default category;